<?php
/**
 * 管理员中心
 * User: Administrator
 * Date: 2017/10/28
 * Time: 13:07
 */

namespace app\admin\controller;


use data\model\User;
use think\Db;
use think\Loader;

class Admin extends Base
{
    /*管理员列表*/
    public function index(){
        $user = new User();
        $result = $user->paginate(10);
        $this->assign('result',$result);
        return $this->fetch('admin/admin/admin');
    }
    /*添加管理员*/
    public function  add(){
        if(request()->post()){
            $data=[
                'username' =>input('username'),
                'password' =>input('password')
            ];
            $file = request()->file('avatar');
            if($file){
                $info = $file->move(ROOT_PATH.__UPLOAD__.'uploads');
                if($info){
                    $data['avatar'] = 'uploads/'.$info->getSaveName();
                }
            }
            $user = new User();
            $res =$user->validate('admin.add')->save($data);
            if(false === $res){
                $this->error($user->getError());exit();
            }
            if($res){
                $this->success('添加成功','index');
            }else{
                $this->error('添加失败');
            }
        }
        return $this->fetch('admin/admin/add');
    }
    /*修改管理员信息*/
    public function edit(){
        $id = input('id');
        $res = User::get($id);
        $this->assign('admin',$res);
        if(request()->post()){
            $data=[
                'username' =>input('username'),
                'userid' =>input('id')
            ];
            $file = request()->file('avatar');
            if($file){
                $info = $file->move(ROOT_PATH.__UPLOAD__.'uploads');
                if($info){
                    $data['avatar'] = 'uploads/'.$info->getSaveName();
                }
            }
            if(input('password')){
                $data['password'] = input('password');
            }else{
                $data['password'] = $res['password'];
            }
            $user = new User();
            $res = $user->isUpdate(true)->validate('admin.edit')->save($data);
            if(false === $res){
                $this->error($user->getError());exit();
            }
            if($res){
                $this->success('修改成功','index');
            }else{
                $this->error('修改失败请重新修改');
            }
        }
        return $this->fetch('admin/admin/edit');
    }
    /* 删除用户*/
    public function del(){
        $id = input('id');
        if(User::destroy($id)){
            $this->success('删除成功','index');
        }else{
            $this->error('删除失败');
        }
    }
}